package cn.chencq.moudle.sys.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.chencq.moudle.sys.dao.BaseDao;
import cn.chencq.moudle.sys.dao.SysUserRoleDao;
import cn.chencq.moudle.sys.entity.SysUserRole;
import cn.chencq.moudle.sys.service.SysUserRoleService;

@Service
public class SysUserRoleServiceImpl extends BaseServiceImpl<SysUserRole> implements SysUserRoleService {

	@Autowired
	private SysUserRoleDao sysUserRoleDao;

	@Override
	protected BaseDao getBaseDao() {
		return sysUserRoleDao;
	}

	@Override
	public List<Long> queryRoleIdList(Long userId) {
		return sysUserRoleDao.queryRoleIdList(userId);
	}

	@Override
	@Transactional
	public void saveOrUpdate(Long userId, List<Long> roleIdList) {
		// 先删除用户与角色关系
		sysUserRoleDao.deleteByUserId(userId);

		if (roleIdList.size() == 0) {
			return;
		}

		// 保存用户与角色关系
		List<SysUserRole> list = new ArrayList<>();
		for (Long roleId : roleIdList) {
			SysUserRole sysUserRole = new SysUserRole();
			sysUserRole.setUserId(userId);
			sysUserRole.setRoleId(roleId);
			list.add(sysUserRole);
		}
		
		sysUserRoleDao.batchSave(list);
	}
}
